package com.agencia.socketserver;

import java.net.*;
import java.sql.SQLException;
import java.io.*;

import javax.naming.NamingException;

import com.agencia.constant.Constants;



public class AgenciaMultiServerThread implements Runnable {
	private Socket socket = null;
	private static errors logSys = errors.getInstance();
	Thread agenciaThread = null;
	
	public AgenciaMultiServerThread(Socket socket) {
		this.socket = socket;

	}
	
	public void start(){
		agenciaThread = new Thread(this);
		agenciaThread.setDaemon(true);
		logSys.writeError(Constants.getLoginok() + " Port:" + Constants.getGlobalParam().get("port"));
		agenciaThread.start();
	}
	

	public void run() {
		try {
			/* Se obtiene un stream de lectura para leer objetos */
	        ObjectInputStream objInput = new ObjectInputStream (socket.getInputStream());
	        ObjectOutputStream objOutput = new ObjectOutputStream (socket.getOutputStream());
	
	        logSys.writeError("Cliente: " + socket.getInetAddress().getHostName() + " Port:" +  Constants.getGlobalParam().get("port")+" "+ Constants.getMsg().get("msg01"));
	
		    AgenciaProtocol agp = new AgenciaProtocol();
		    Object outputObject = agp.processInput(objInput, socket.getInetAddress().getHostName());
		    logSys.writeError(agp.getStrin());
	        
		    logSys.writeError("Cliente: " + socket.getInetAddress().getHostName() + " Port:" +  Constants.getGlobalParam().get("port")+" "+ Constants.getMsg().get("msg02") +" " + agp.getStrout());
	
		    objOutput.writeObject(outputObject);
	
		    objInput.close();
		    objOutput.close();
		    socket.close();
		
		} catch (IOException e) {
	        logSys.writeError("Cliente: " + socket.getInetAddress().getHostName() + " Port:" +  Constants.getGlobalParam().get("port")+" "+ e.getMessage());
	        
		} catch (ClassNotFoundException e) {
	        logSys.writeError("Cliente: " + socket.getInetAddress().getHostName() + " Port:" +  Constants.getGlobalParam().get("port")+" "+ e.getMessage());
	        
		} catch (SQLException e) {
	        logSys.writeError("Cliente: " + socket.getInetAddress().getHostName() + " Port:" +  Constants.getGlobalParam().get("port")+" "+ e.getMessage());
		
		} catch (NamingException e) {
			logSys.writeError("Cliente: " + socket.getInetAddress().getHostName() + " Port:" +  Constants.getGlobalParam().get("port")+" "+ e.getMessage());
	
		}
	}

}
